<template>
  <pre>
    <code class="language-javascript" v-html="highlightedCodeHTML"></code>
    <el-button class="copy" size="small" @click="copyCode">复制代码</el-button>
  </pre>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import hljs from 'highlight.js'
import 'highlight.js/styles/stackoverflow-dark.css'

const { code, language } = defineProps({
  code: {
    type: String,
    default: ''
  },
  language: {
    type: String,
    default: 'javascript'
  }
})

const highlightedCode = hljs.highlight(code, { language })
const highlightedCodeHTML = highlightedCode.value

const copyCode = async () => {
  try {
    await navigator.clipboard.writeText(code)
    ElMessage.success('copy success')
  } catch (err) {
    console.log('🚀 ~ copyCode ~ err:', err)
    ElMessage.error('copy failed')
  }

}
</script>